/**
 * Created by jiangyukun on 2016/5/23.
 */
'use strict';
app.controller('AccountInfoController', function (iHttp, $uibModal) {
    var self = this;

    this.currentPage = 1;
    this.pageTotal = 0;
    this.draw = 0;
    this.recordsTotal = 0;
    this.detailInfo = detailInfo;
    this.toPage = toPage;
    this.beforePage = beforePage;
    this.nextPage = nextPage;

    getServerData();

    function getServerData() {
        var draw = self.draw;
        var length = 10;
        var start = (self.currentPage - 1) * length;
        iHttp.get('mock/json/info.json', {draw: draw, start: start, length: length}).then(function (result) {
            var data = result.data;
            if (data.draw < self.draw) {
                return;
            }
            self.recordsTotal = data.recordsTotal;
            self.pageTotal = parseInt((data.recordsTotal + length - 1) / length);
            self.pages = getPagesToShow(self.pageTotal);
            self.accounts = data.data;
        });
        self.draw++;
    }

    function toPage(page) {
        self.currentPage = page;
        getServerData();
    }

    function beforePage() {
        if (self.currentPage > 1) {
            self.currentPage--;
            getServerData();
        }
    }

    function nextPage() {
        if (self.currentPage < self.pageTotal) {
            self.currentPage++;
            getServerData();
        }
    }


    function detailInfo() {
        $uibModal.open({
            templateUrl: 'tpl/account/detail_info_dialog.html',
            controller: 'DetailInfoController'
        });
    }

    function getPagesToShow(pageTotal) {
        var i, j, pageToShowLength = 5;
        var beforeCount = 4, afterCount, current = self.currentPage;
        var pages = [];

        if (pageTotal < 1) {
            return [];
        }
        else if (pageTotal == 1) {
            return [1];
        }
        pages.push(1);

        var start = current - beforeCount;
        if (start < 2) {
            start = 2;
            beforeCount = current - 2;
            if (beforeCount < 0) {
                beforeCount = 0;
            }
        } else if (start > 2) {
            pages.push('...')
        }
        for (i = start; i <= current; i++) {
            pages.push(i);
        }
        afterCount = pageToShowLength - beforeCount;
        for (i = current + 1, j = 0; i < pageTotal; i++) {
            if (j > afterCount) {
                if (i != pageTotal - 1) {
                    pages.push('...');
                }
                break;
            }
            pages.push(i);
            j++;
        }
        pages.push(pageTotal);
        return pages;
    }
});

app.controller('DetailInfoController', function ($scope, $uibModalInstance) {
    $scope.close = close;


    function close() {
        $uibModalInstance.close();
    }
});